package com.yupi.springbootinit.manager;


import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author FengHuan Wang
 * @Date 2025/2/9 9:57
 * @Version 1.0
 */
@Component
public class RedissonManager {

    @Resource
    private RedissonClient redissonClient;


    public void doLimit(String key){

        // 创建或获取限流器实例
        RRateLimiter rateLimiter = redissonClient.getRateLimiter(key);
        // 设置限流规则：每秒最多5个许可，每个用户最多每秒1个许可
        rateLimiter.trySetRate(RateType.OVERALL, 5, 1, RateIntervalUnit.SECONDS);

        // 尝试获取许可,每当一个请求来了之后，请求2个令牌
        boolean tryAcquire = rateLimiter.tryAcquire(2);
        if (!tryAcquire){
            throw new BusinessException(ErrorCode.TOO_MANY_REQUEST);
        }
    }
}
